<template>
  <div :id="node.id" ref="nodeRef" class="flow-node" :class="[`${node.type}-node`, { selected: isSelected }]" :style="{
    left: `${node.position.x}px`,
    top: `${node.position.y}px`,
  }" @click.stop="$emit('select', node.id)" :data-node-id="node.id">
    <div class="node-header">
      <i :class="getNodeIcon"></i>
      <span class="node-title">{{ node.name || getDefaultName }}</span>
    </div>
    <div class="node-content">
      <!-- 根据节点类型显示不同的内容 -->
      <template v-if="node.type === 'model'">
        <div class="model-info">
          <div class="model-type">
            <i class="fas fa-cog"></i>
            <span>{{ node.modelType }}</span>
          </div>
          <div class="model-prompt">
            {{ node.prompt ? (node.prompt.length > 50 ? node.prompt.substring(0, 50) + '...' : node.prompt) : '未设置提示词'
            }}
          </div>
        </div>
      </template>

      <template v-else-if="node.type === 'agent'">
        <div class="agent-info">
          <i class="fas fa-tools"></i>
          <span>可用工具: {{ node.tools?.length || 0 }}</span>
        </div>
      </template>

      <template v-else-if="node.type === 'code'">
        <div class="code-info">
          <i class="fas fa-code"></i>
          <span>{{ node.language }}</span>
        </div>
      </template>

      <template v-else-if="node.type === 'ifelse'">
        <div class="condition-info">
          <i class="fas fa-question-circle"></i>
          <span>{{ node.condition || '未设置条件' }}</span>
        </div>
      </template>

      <template v-else-if="node.type === 'iterator'">
        <div class="iterator-info">
          <i class="fas fa-list"></i>
          <span>迭代键: {{ node.iterationKey }}</span>
        </div>
      </template>

      <template v-else-if="node.type === 'template'">
        <div class="template-info">
          <i class="fas fa-file-alt"></i>
          <span>模板转换</span>
        </div>
      </template>

      <template v-else-if="node.type === 'http'">
        <div class="http-info">
          <i class="fas fa-globe"></i>
          <span>{{ node.method }} {{ node.url || '未设置URL' }}</span>
        </div>
      </template>

      <template v-else-if="node.type === 'database'">
        <div class="db-info">
          <i class="fas fa-database"></i>
          <span>数据库查询</span>
        </div>
      </template>

      <template v-else-if="node.type === 'email'">
        <div class="email-info">
          <i class="fas fa-envelope"></i>
          <span>{{ node.emailConfig?.subject || '未设置主题' }}</span>
        </div>
        <div class="email-recipients" v-if="node.emailConfig?.recipients?.length">
          <i class="fas fa-user"></i>
          <span>收件人: {{ node.emailConfig.recipients.length }}人</span>
        </div>
      </template>

      <!-- 参数预览 -->
      <div v-if="hasParams" class="params-preview">
        <div v-if="node.params.input.length > 0" class="input-preview">
          <i class="fas fa-arrow-right"></i>
          输入: {{ node.params.input.length }}项
        </div>
        <div v-if="node.params.output.length > 0" class="output-preview">
          <i class="fas fa-arrow-left"></i>
          输出: {{ node.params.output.length }}项
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import type { Node } from '../types';

const props = defineProps<{
  node: Node;
  isSelected: boolean;
}>();

const emit = defineEmits<{
  (e: 'select', id: string): void;
  (e: 'update:position', id: string, position: { x: number; y: number }): void;
  (e: 'delete', id: string): void;
}>();

const nodeRef = ref<HTMLElement | null>(null);
let isDragging = false;
let startX = 0;
let startY = 0;
let originalX = 0;
let originalY = 0;

const getNodeIcon = computed(() => {
  const iconMap: Record<string, string> = {
    start: 'fas fa-play-circle',
    model: 'fas fa-brain',
    end: 'fas fa-stop-circle',
    agent: 'fas fa-robot',
    ifelse: 'fas fa-code-branch',
    iterator: 'fas fa-redo',
    code: 'fas fa-code',
    template: 'fas fa-file-alt',
    http: 'fas fa-globe',
    database: 'fas fa-database',
    email: 'fas fa-envelope',
  };
  return iconMap[props.node.type] || 'fas fa-question-circle';
});

const getDefaultName = computed(() => {
  const nameMap: Record<string, string> = {
    start: '开始节点',
    model: '大模型节点',
    end: '结果节点',
    agent: '智能体节点',
    ifelse: '条件判断节点',
    iterator: '迭代器节点',
    code: '代码节点',
    template: '模板转换节点',
    http: 'HTTP节点',
    database: '数据库节点',
    email: '邮件节点',
  };
  return nameMap[props.node.type] || '未知节点';
});

const hasParams = computed(() => {
  return props.node.params.input.length > 0 || props.node.params.output.length > 0;
});

// 初始化拖动
const initDrag = () => {
  if (!nodeRef.value) return;

  const handleMouseDown = (e: MouseEvent) => {
    // 如果点击的是端点或其父元素，不启动拖动
    if ((e.target as Element).closest('.jtk-endpoint') || (e.target as Element).closest('.delete-btn')) {
      return;
    }

    isDragging = true;
    startX = e.clientX;
    startY = e.clientY;
    originalX = props.node.position.x;
    originalY = props.node.position.y;

    // 添加拖动状态样式
    if (nodeRef.value) {
      nodeRef.value.classList.add('dragging');
    }

    const handleMouseMove = (e: MouseEvent) => {
      if (!isDragging) return;

      const dx = e.clientX - startX;
      const dy = e.clientY - startY;

      const newX = originalX + dx;
      const newY = originalY + dy;

      // 更新节点位置
      emit('update:position', props.node.id, { x: newX, y: newY });
    };

    const handleMouseUp = () => {
      isDragging = false;

      // 移除拖动状态样式
      if (nodeRef.value) {
        nodeRef.value.classList.remove('dragging');
      }

      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    };

    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);
  };

  nodeRef.value.addEventListener('mousedown', handleMouseDown);
};

// 在组件挂载后初始化拖动
onMounted(() => {
  initDrag();
});
</script>

<style scoped>
.flow-node {
  position: absolute;
  min-width: 200px;
  background: white;
  border: 2px solid #e9ecef;
  border-radius: 12px;
  padding: 0;
  cursor: move;
  user-select: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: box-shadow 0.2s ease;

  &:hover {
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.12);
  }

  &.dragging {
    opacity: 0.9;
    box-shadow: 0 12px 20px rgba(0, 0, 0, 0.15);
  }
}

.flow-node.selected {
  border-width: 2px;
  border-color: #4e9bf8;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.12);
}

.node-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 14px;
  position: relative;
  overflow: hidden;
  backdrop-filter: blur(4px);
}

.node-header::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  opacity: 0.15;
  z-index: 0;
}

.node-header i {
  position: relative;
  z-index: 1;
  font-size: 18px;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 10px;
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.08);
}

.flow-node:hover .node-header i {
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.12);
}

.node-title {
  position: relative;
  z-index: 1;
  font-weight: 600;
  font-size: 14px;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #2c3e50;
}

.delete-btn {
  position: relative;
  z-index: 2;
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  background: rgba(255, 255, 255, 0.8);
  color: #dc3545;
  border-radius: 50%;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s ease;
  opacity: 0;
  transform: scale(0.8);
}

.flow-node:hover .delete-btn {
  opacity: 1;
  transform: scale(1);
}

.delete-btn:hover {
  background: #dc3545;
  color: white;
  box-shadow: 0 2px 4px rgba(220, 53, 69, 0.3);
}

.node-content {
  padding: 14px;
  font-size: 13px;
  color: #6c757d;
  border-top: 1px solid #f1f3f5;
  background: linear-gradient(to bottom, #ffffff, #f9fafb);
}

.model-info,
.agent-info,
.code-info,
.condition-info,
.iterator-info,
.template-info,
.http-info,
.db-info,
.email-info,
.email-recipients {
  margin-bottom: 10px;
  padding: 8px 10px;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.7);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.2s ease;
}

.model-info:hover,
.agent-info:hover,
.code-info:hover,
.condition-info:hover,
.iterator-info:hover,
.template-info:hover,
.http-info:hover,
.db-info:hover,
.email-info:hover,
.email-recipients:hover {
  background: rgba(255, 255, 255, 0.9);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.06);
}

.params-preview {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #f1f3f5;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.input-preview,
.output-preview {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 10px;
  border-radius: 8px;
  background: #f8f9fa;
  font-size: 13px;
  transition: all 0.2s ease;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.input-preview:hover,
.output-preview:hover {
  background: #f1f3f5;
}

.input-preview i,
.output-preview i {
  font-size: 13px;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  background: rgba(0, 123, 255, 0.1);
  color: #007bff;
}

.input-preview:hover i,
.output-preview:hover i {
  color: #0069d9;
}

/* 节点类型特定样式 */
.start-node {
  border-color: rgba(40, 167, 69, 0.3);

  .node-header {
    color: #28a745;

    &::before {
      background: linear-gradient(135deg, #28a745, #34ce57);
    }

    i {
      color: #28a745;
      background: rgba(40, 167, 69, 0.15);
    }
  }
}

.model-node {
  border-color: rgba(0, 123, 255, 0.3);

  .node-header {
    color: #007bff;

    &::before {
      background: linear-gradient(135deg, #007bff, #1a88ff);
    }

    i {
      color: #007bff;
      background: rgba(0, 123, 255, 0.15);
    }
  }
}

.end-node {
  border-color: rgba(220, 53, 69, 0.3);

  .node-header {
    color: #dc3545;

    &::before {
      background: linear-gradient(135deg, #dc3545, #e4606d);
    }

    i {
      color: #dc3545;
      background: rgba(220, 53, 69, 0.15);
    }
  }
}

.agent-node {
  border-color: rgba(111, 66, 193, 0.3);

  .node-header {
    color: #6f42c1;

    &::before {
      background: linear-gradient(135deg, #6f42c1, #8458cd);
    }

    i {
      color: #6f42c1;
      background: rgba(111, 66, 193, 0.15);
    }
  }
}

.ifelse-node {
  border-color: rgba(253, 126, 20, 0.3);

  .node-header {
    color: #fd7e14;

    &::before {
      background: linear-gradient(135deg, #fd7e14, #fd9843);
    }

    i {
      color: #fd7e14;
      background: rgba(253, 126, 20, 0.15);
    }
  }
}

.iterator-node {
  border-color: rgba(32, 201, 151, 0.3);

  .node-header {
    color: #20c997;

    &::before {
      background: linear-gradient(135deg, #20c997, #3dd5ac);
    }

    i {
      color: #20c997;
      background: rgba(32, 201, 151, 0.15);
    }
  }
}

.code-node {
  border-color: rgba(108, 117, 125, 0.3);

  .node-header {
    color: #6c757d;

    &::before {
      background: linear-gradient(135deg, #6c757d, #868e96);
    }

    i {
      color: #6c757d;
      background: rgba(108, 117, 125, 0.15);
    }
  }
}

.template-node {
  border-color: rgba(23, 162, 184, 0.3);

  .node-header {
    color: #17a2b8;

    &::before {
      background: linear-gradient(135deg, #17a2b8, #1fc8e3);
    }

    i {
      color: #17a2b8;
      background: rgba(23, 162, 184, 0.15);
    }
  }
}

.http-node {
  border-color: rgba(232, 62, 140, 0.3);

  .node-header {
    color: #e83e8c;

    &::before {
      background: linear-gradient(135deg, #e83e8c, #ed5fa1);
    }

    i {
      color: #e83e8c;
      background: rgba(232, 62, 140, 0.15);
    }
  }
}

.database-node {
  border-color: rgba(121, 85, 72, 0.3);

  .node-header {
    color: #795548;

    &::before {
      background: linear-gradient(135deg, #795548, #936860);
    }

    i {
      color: #795548;
      background: rgba(121, 85, 72, 0.15);
    }
  }
}

.email-node {
  border-color: rgba(156, 39, 176, 0.3);

  .node-header {
    color: #9C27B0;

    &::before {
      background: linear-gradient(135deg, #9C27B0, #BA68C8);
    }

    i {
      color: #9C27B0;
      background: rgba(156, 39, 176, 0.15);
    }
  }
}

.email-info,
.email-recipients {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.email-info i,
.email-recipients i {
  color: #9C27B0;
  width: 16px;
  text-align: center;
}

/* 样式优先级 */
.jtk-connector {
  z-index: 5;
}

.jtk-endpoint {
  z-index: 10;
}

.jtk-overlay {
  z-index: 11;
}
</style>